﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "外协入库管理";
    Layout = null;
}

@Html.AntiForgeryToken()

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>外协入库管理</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="searchForm" lay-filter="searchForm" style="margin-bottom:10px;max-width:100%;">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">入库单编号</label>
                        <div class="layui-input-inline" style="width:180px;">
                            <input type="text" name="InOrderCode" placeholder="请输入入库单编号" autocomplete="off" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">外协工单</label>
                        <div class="layui-input-inline" style="width:180px;">
                            <input type="text" name="OutsourcedOrders" placeholder="请输入外协工单" autocomplete="off" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">供应商</label>
                        <div class="layui-input-inline" style="width:180px;">
                            <input type="text" name="Vendor" placeholder="请输入供应商" autocomplete="off" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">入库日期</label>
                        <div class="layui-input-inline" style="width:150px;">
                            <input type="date" name="InOrderDate" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline" style="float:right;">
                        <button type="submit" class="layui-btn layui-btn-sm" lay-submit lay-filter="searchForm">查询</button>
                        <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">重置</button>
                    </div>
                </div>
            </form>

            <div class="layui-btn-group">
                <button class="layui-btn" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 添加
                </button>
                <button class="layui-btn" id="batchDeleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 批量删除
                </button>
            </div>

            <table id="mainTable" lay-filter="mainTable"></table>
        </div>
    </div>
</div>

<!-- 弹窗表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="__RequestVerificationToken" />
        <input type="hidden" name="Id" />
        <div class="layui-form-item">
            <label class="layui-form-label required">入库单编号</label>
            <div class="layui-input-block" style="display:flex;align-items:center;gap:8px;">
                <input type="text" name="InOrderCode" required lay-verify="required" placeholder="请输入入库单编号" autocomplete="off" class="layui-input" maxlength="50" style="flex:1;" />
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="autoGenInOrderCodeBtn">自动生成</button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">入库单名称</label>
            <div class="layui-input-block">
                <input type="text" name="InOrderName" required lay-verify="required" placeholder="请输入入库单名称" autocomplete="off" class="layui-input" maxlength="50" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">入库日期</label>
            <div class="layui-input-block">
                <input type="date" name="InOrderDate" required lay-verify="required" class="layui-input" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">外协工单</label>
            <div class="layui-input-block">
                <input type="text" name="OutsourcedOrders" required lay-verify="required" placeholder="请输入外协工单" autocomplete="off" class="layui-input" maxlength="50" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">单据状态</label>
            <div class="layui-input-block">
                <select name="State" lay-verify="required" disabled>
                    <option value="">请选择状态</option>
                    <option value="0"  selected  >草稿</option>
                    <option value="1">已提交</option>
                    <option value="2">已完成</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">采购订单号</label>
            <div class="layui-input-block">
                <input type="text" name="PurchaseOrderCode" placeholder="请输入采购订单号" autocomplete="off" class="layui-input" maxlength="50" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">供应商</label>
            <div class="layui-input-block">
                <input type="text" name="Vendor" required lay-verify="required" placeholder="请输入供应商" autocomplete="off" class="layui-input" maxlength="50" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">入库仓库</label>
            <div class="layui-input-block">
                <input type="text" name="InboundWarehouse" placeholder="请输入入库仓库" autocomplete="off" class="layui-input" maxlength="50" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input type="text" name="Remark" placeholder="请输入备注" autocomplete="off" class="layui-input" maxlength="100" />
            </div>
        </div>
        <div class="layui-form-item" style="text-align:right;">
            <button class="layui-btn" id="submitBtn" lay-submit>提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
    layui.use(['table', 'form', 'layer'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;

        // 初始化表格
        function loadTable(params) {
            var searchParams = params || {};
            searchParams.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();

            table.render({
                elem: '#mainTable',
                url: '/OutsourcingWarehousing/GetList',
                method: 'get',
                where: searchParams,
                page: true,
                cols: [[
                    {type: 'checkbox', fixed: 'left', width: 50},
                    {field: 'id', title: 'ID', width: 120},
                    {field: 'inOrderCode', title: '入库单编号', width: 120},
                    {field: 'inOrderName', title: '入库单名称', width: 120},
                    {field: 'inOrderDate', title: '入库日期', width: 120, templet: function(d){
                        return d.inOrderDate ? d.inOrderDate.split('T')[0] : '';
                    }},
                    {field: 'outsourcedOrders', title: '外协工单', width: 120},
                    {field: 'state', title: '单据状态', width: 100, templet: function(d){
                        var states = ['草稿', '已提交', '已完成'];
                        return states[d.state] || '未知';
                    }},
                    {field: 'purchaseOrderCode', title: '采购订单号', width: 120},
                    {field: 'vendor', title: '供应商', width: 120},
                    {field: 'inboundWarehouse', title: '入库仓库', width: 120},
                    {field: 'remark', title: '备注'},
                    {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 200}
                ]],
                response: {
                    statusCode: 0
                },
                parseData: function(res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                }
            });
        }

        // 加载初始数据
        loadTable();

        // 搜索按钮点击事件
        form.on('submit(searchForm)', function(data){
            loadTable(data.field);
            return false;
        });

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            openForm();
        });

        // 打开表单
        function openForm(data, isEdit) {
            var title = isEdit ? '修改外协入库' : (data ? '编辑外协入库' : '添加外协入库');
            layer.open({
                type: 1,
                title: title,
                area: ['500px', '600px'],
                content: $('#formTpl').html(),
                success: function(layero, index){
                    form.render(null, 'mainForm');
                    // 动态设置按钮lay-filter
                    var filter = isEdit ? 'submitEdit' : 'submitAdd';
                    $(layero).find('#submitBtn').attr('lay-filter', filter);
                    if(data){
                        form.val('mainForm', {
                            "Id": data.id,
                            "InOrderCode": data.inOrderCode,
                            "InOrderName": data.inOrderName,
                            "InOrderDate": data.inOrderDate ? data.inOrderDate.split('T')[0] : '',
                            "OutsourcedOrders": data.outsourcedOrders,
                            "State": data.state,
                            "PurchaseOrderCode": data.purchaseOrderCode,
                            "Vendor": data.vendor,
                            "InboundWarehouse": data.inboundWarehouse,
                            "Remark": data.remark
                        });
                    }
                    // 监听提交（编辑）
                    form.on('submit(submitEdit)', function(formData){
                        var loadIndex = layer.load(2);
                        var submitData = {
                            Id: formData.field.Id,
                            InOrderCode: formData.field.InOrderCode,
                            InOrderName: formData.field.InOrderName,
                            InOrderDate: formData.field.InOrderDate,
                            OutsourcedOrders: formData.field.OutsourcedOrders,
                            State: parseInt(formData.field.State),
                            PurchaseOrderCode: formData.field.PurchaseOrderCode || '',
                            Vendor: formData.field.Vendor,
                            InboundWarehouse: formData.field.InboundWarehouse || '',
                            Remark: formData.field.Remark || '',
                            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                        };
                        $.ajax({
                            url: '/OutsourcingWarehousing/Update?id=' + formData.field.Id,
                            type: 'POST',
                            data: submitData,
                            success: function(res){
                                layer.close(loadIndex);
                                if(res.code === 0){
                                    layer.close(index);
                                    setTimeout(function(){layer.msg('修改成功');}, 200);
                                    table.reload('mainTable');
                                } else {
                                    layer.msg(res.msg || '修改失败');
                                }
                            },
                            error: function(xhr){
                                layer.close(loadIndex);
                                layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                            }
                        });
                        return false;
                    });
                    // 监听提交（新增）
                    form.on('submit(submitAdd)', function(formData){
                        var loadIndex = layer.load(2);
                        var submitData = {
                            InOrderCode: formData.field.InOrderCode,
                            InOrderName: formData.field.InOrderName,
                            InOrderDate: formData.field.InOrderDate,
                            OutsourcedOrders: formData.field.OutsourcedOrders,
                            State: parseInt(formData.field.State),
                            PurchaseOrderCode: formData.field.PurchaseOrderCode || '',
                            Vendor: formData.field.Vendor,
                            InboundWarehouse: formData.field.InboundWarehouse || '',
                            Remark: formData.field.Remark || '',
                            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                        };
                        $.ajax({
                            url: '/OutsourcingWarehousing/Add',
                            type: 'POST',
                            data: submitData,
                            success: function(res){
                                layer.close(loadIndex);
                                if(res.code === 0){
                                    layer.close(index);
                                    setTimeout(function(){layer.msg('添加成功');}, 200);
                                    table.reload('mainTable');
                                } else {
                                    layer.msg(res.msg || '添加失败');
                                }
                            },
                            error: function(xhr){
                                layer.close(loadIndex);
                                layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                            }
                        });
                        return false;
                    });

                    // 在 openForm 的 success 回调里添加自动生成按钮事件
                    $(layero).find('#autoGenInOrderCodeBtn').on('click', function(){
                        var btn = $(this);
                        btn.prop('disabled', true).text('生成中...');
                        $.get('/OutsourcingWarehousing/GetInOrderCode', function(res){
                            btn.prop('disabled', false).text('自动生成');
                            if(res.code === 0 && res.inOrderCode){
                                $(layero).find('input[name="InOrderCode"]').val(res.inOrderCode);
                            }else{
                                layer.msg(res.msg || '生成失败');
                            }
                        }).fail(function(){
                            btn.prop('disabled', false).text('自动生成');
                            layer.msg('生成失败');
                        });
                    });
                }
            });
        }

        // 修改状态按钮事件
        $(document).on('click', '.update-state-btn', function(){
            var id = $(this).data('id');
            var state = $(this).data('state');
            $.ajax({
                url: '/OutsourcingWarehousing/UpdateState',
                type: 'POST',
                data: {
                    id: id,
                    state: state,
                    __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                },
                success: function(res){
                    if(res.code === 0){
                        layer.msg('状态修改成功');
                        table.reload('mainTable');
                    }else{
                        layer.msg(res.msg || '修改失败');
                    }
                }
            });
        });

        // 批量删除按钮点击事件
        $('#batchDeleteBtn').on('click', function(){
            var checkStatus = table.checkStatus('mainTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要删除的记录');
                return;
            }
            // 过滤掉已完成的
            var deletable = data.filter(function(item){ return item.state !== 2; });
            if(deletable.length === 0){
                layer.msg('已完成的记录不能删除');
                return;
            }
            var ids = deletable.map(function(item){ return item.id; });
            layer.confirm('确定要删除选中的'+ids.length+'条记录吗？', function(index){
                $.ajax({
                    url: '/OutsourcingWarehousing/BatchDelete',
                    type: 'POST',
                    data: {
                        ids: ids,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('成功删除' + ids.length + '条记录');
                            table.reload('mainTable');
                        }else{
                            layer.msg(res.msg || '删除失败');
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 事件绑定：修改和删除
        $(document).on('click', '.edit-btn', function(){
            var id = $(this).data('id');
            // 获取数据并弹窗反填
            $.get('/OutsourcingWarehousing/GetById', { id: id }, function(res){
                if(res.code === 0 && res.data){
                    openForm(res.data, true); // true表示编辑模式
                }else{
                    layer.msg(res.msg || '获取数据失败');
                }
            });
        });

        $(document).on('click', '.delete-btn', function(){
            var id = $(this).data('id');
            layer.confirm('确定要删除此记录吗？', function(index){
                $.ajax({
                    url: '/OutsourcingWarehousing/Delete',
                    type: 'POST',
                    data: {
                        id: id,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('删除成功');
                            table.reload('mainTable');
                        }else{
                            layer.msg(res.msg || '删除失败');
                        }
                    }
                });
                layer.close(index);
            });
        });
    });
</script>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
  {{#  if(d.state == 0){ }}
    <a class="layui-btn layui-btn-xs layui-btn-normal update-state-btn" data-id="{{d.id}}" data-state="2">设为完成</a>
    <a class="layui-btn layui-btn-xs layui-btn-primary edit-btn" data-id="{{d.id}}">修改</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger delete-btn" data-id="{{d.id}}">删除</a>
  {{#  } else if(d.state == 1){ }}
    <a class="layui-btn layui-btn-xs layui-btn-primary edit-btn" data-id="{{d.id}}">修改</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger delete-btn" data-id="{{d.id}}">删除</a>
  {{#  } }}
</script>

<style>
    .layui-form-label.required:after {
        content: '*';
        color: red;
        margin-left: 4px;
    }

    .layui-card {
        margin: 15px;
    }

    .layui-form-item {
        margin-bottom: 15px;
    }

    .layui-btn-group {
        float: right;
        margin-bottom: 10px;
    }
    .layui-btn-group .layui-btn {
        margin-left: 8px;
    }
    #batchDeleteBtn {
        background: #ff4d4f;
        color: #fff;
        border: none;
    }
    #batchDeleteBtn:hover {
        background: #ff7875;
        color: #fff;
    }
</style>
